package dao

import (
	"app.com/rpc.v1/config"
	"github.com/go-redis/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormLogger "gorm.io/gorm/logger"
	"log"
)

type Dao struct {
	Db       *gorm.DB
	RedisCli *redis.Client
}

func NewDao() *Dao {
	return &Dao{
		RedisCli: newRedis(),
		Db:       newDb(),
	}
}

func newDb() *gorm.DB {
	db, err := gorm.Open(mysql.Open(config.AppConf.MysqlConf.Source), &gorm.Config{
		Logger: gormLogger.Default.LogMode(gormLogger.Info),
	})
	if err != nil {
		log.Fatalf("mysql connect error: %v", err)
	}
	return db
}

func newRedis() *redis.Client {
	rdb := redis.NewClient(config.AppConf.RedisConf)
	err := rdb.Ping().Err()
	if err != nil {
		log.Fatalf("mysql connect error: %v", err)
	}
	return rdb
}
